package mickey;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

public class DataAccess {

	static String treiber = "com.mysql.jdbc.Driver";
	static String DbUrl = "jdbc:mysql://localhost:3306/mickey";

	public static void addToDatabase(String update) {

		try {
			Class.forName(treiber).newInstance();
			Connection cn = DriverManager.getConnection(DbUrl, "root", "test1");
			try {
				Statement st = cn.createStatement();
				st.executeUpdate(update);
				st.close();
			} catch (SQLException ex) {
				System.out.println(ex);
			}
			cn.close();
		} catch (Exception ex) {
			System.out.println(ex);
		}
	}
	
	public static String getLatestID() {

		String lastid="null";
		try {
			Class.forName(treiber).newInstance();
			Connection cn = DriverManager.getConnection(DbUrl, "root", "test1");
			ResultSet rs = null;
			try {
				Statement st = cn.createStatement();
				rs=st.executeQuery("SELECT LAST_INSERT_ID();");
				rs.next();
				lastid=rs.getString("LAST_INSERT_ID()");
				st.close();
			} catch (SQLException ex) {
				System.out.println(ex);
			}
			cn.close();
		} catch (Exception ex) {
			System.out.println(ex);
		}
		return lastid;
	}

	public static ArrayList<MickeyMausHeft> getFromDatabase(String select) {

		try {
			Class.forName(treiber).newInstance();
			Connection cn = DriverManager.getConnection(DbUrl, "root", "test1");
			ResultSet rs = null;
			ArrayList<MickeyMausHeft> resultArrayList = null;
			try {
				Statement st = cn.createStatement();
				rs = st.executeQuery(select);
				resultArrayList = new ArrayList<MickeyMausHeft>(100);
				while (rs.next()) {
					MickeyMausHeft mmheft = new MickeyMausHeft(
							rs.getString("name"),
							rs.getString("erscheinungsjahr"));
					resultArrayList.add(mmheft);
				}
				st.close();
			} catch (SQLException ex) {
				System.out.println(ex);
			}
			return resultArrayList;
		} catch (Exception ex) {
			System.out.println(ex);
		}
		return null;
	}

}
